import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/widgets.dart';
import '../servie/service_method.dart';
import 'dart:convert'; //数据解析

import 'package:flutter_swiper/flutter_swiper.dart'; //轮播插件
import 'package:flutter_screenutil/flutter_screenutil.dart'; //屏幕适配方案
import 'package:url_launcher/url_launcher.dart'; //打电话插件
import 'package:flutter_easyrefresh/easy_refresh.dart'; //上拉加载 下拉刷新

import 'package:transparent_image/transparent_image.dart';//占位图；

import '../routers/application.dart';
import 'package:fluro/fluro.dart';
class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}
/*
 * AutomaticKeepAliveClientMixin这个Mixin就是Flutter为了保持页面设置的。
 * 哪个页面需要保持页面状态，就在这个页面进行混入。
 *
 *不过使用使用这个Mixin是有几个先决条件的：
 *--使用的页面必须是StatefulWidget,如果是StatelessWidget是没办法办法使用的。
 *--其实只有两个前置组件才能保持页面状态：PageView和IndexedStack。
 *--重写wantKeepAlive方法，如果不重写也是实现不了的。
 */
class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {

  int page = 1; //火爆专区页数
  List<Map> hotGoodsList =new List(); //火爆专区数据
  GlobalKey<EasyRefreshState> _easyRefreshKey =new GlobalKey<EasyRefreshState>();
  GlobalKey<RefreshFooterState> _footerkey = new GlobalKey<RefreshFooterState>();
  GlobalKey<RefreshHeaderState> _headerKey =new GlobalKey<RefreshHeaderState>();
  @override
  bool get wantKeepAlive => true;

  String homePageContent = '正在获取数据';

  @override
  void initState() {
    super.initState();
    _getHotlist();
    print('首页加载');
  }

  @override
  Widget build (BuildContext context) {
    return Container(
       child: Scaffold(
         appBar: AppBar(
           title: Text('百姓生活+'),
           centerTitle: true,
         ),
         body:FutureBuilder(
             future:requset('homePageContent',formData:{'lon':'115.02932','lat':'35.76189'}),
             builder: (context,snapshot){
               if(snapshot.hasData){
                 //数据处理
                 var data = json.decode(snapshot.data.toString());
                 List<Map> swiper = (data['data']['slides'] as List ).cast(); //轮播数据
                 List<Map> navigatorList = (data['data']['category'] as List).cast();//导航数据
                 String adpictute = data['data']['advertesPicture']['PICTURE_ADDRESS'] as String;//小广告数据
                 String leaderImage = data['data']['shopInfo']['leaderImage'] as String;//店长图片
                 String leaderPhone = data['data']['shopInfo']['leaderPhone'] as String;//店长电话
                 List<Map> recommendList = (data['data']['recommend'] as List).cast();//商品推荐数据
                 String floorTitlle = data['data']['floor1Pic']['PICTURE_ADDRESS'] as String;//楼层1的标题
                 List<Map> floorGoodsList = (data['data']['floor1'] as List ).cast();//楼层1的图片list
                 String floor2Titlle = data['data']['floor2Pic']['PICTURE_ADDRESS'] as String;//楼层1的标题
                 List<Map> floor2GoodsList = (data['data']['floor2'] as List ).cast();//楼层1的图片list
                 String floor3Titlle = data['data']['floor3Pic']['PICTURE_ADDRESS'] as String;//楼层1的标题
                 List<Map> floor3GoodsList = (data['data']['floor3'] as List ).cast();//楼层1的图片list

                 return EasyRefresh(
                    key: _easyRefreshKey,
                    behavior: ScrollOverBehavior(),
                    refreshFooter: ClassicsFooter(
                      key:_footerkey,
                      loadText:'上拉加载更多',// 提示加载文字
                      loadReadyText: '松手加载更多', // 准备加载文字
                      loadingText:'加载中...',// 正在加载文字
                      noMoreText: '加载成功',// 没有更多文字
                      loadedText:'加载成功',//刷新完成文字
                      moreInfo: '加载中...',//更多信息文字颜色

                      bgColor: Colors.white,//背景颜色
                      textColor: Colors.pink,//字体颜色
                      moreInfoColor: Colors.pink,
                      showMore: false,//显示额外信息默认为时间
                    ),
                    refreshHeader: ClassicsHeader(
                      key: _headerKey,
                      bgColor: Colors.white,//背景颜色
                      textColor: Colors.pink,//字体颜色
                      moreInfoColor: Colors.pink,
                      showMore: false,//显示额外信息默认为时间
                      refreshText:'下拉刷新',// 提示刷新文字
                      refreshReadyText:'松手刷新',//准备刷新文字
                      refreshingText:'正在刷新',//正在刷新文字
                      refreshedText:'刷新完成'//刷新完成文字
                    ),
                   child:ListView(
                      children: <Widget>[
                        SwiperDiy(swiperDateList:swiper),
                        TopNavgator(navigatorList:navigatorList),
                        AdBanner(adpictute:adpictute),
                        LeaderPhone(leaderImage:leaderImage,leaderPhone:leaderPhone),
                        Recommend(recmmendList:recommendList),
                        FloorTitle(pictureaddress: floorTitlle),
                        FloorContent(floorGoodsList: floorGoodsList),
                        FloorTitle(pictureaddress: floor2Titlle),
                        FloorContent(floorGoodsList: floor2GoodsList),
                        FloorTitle(pictureaddress: floor3Titlle),
                        FloorContent(floorGoodsList: floor3GoodsList),
                        _hotGoods()
                      ],
                    ),
                    loadMore: () async {
                      print('开始加载更多');
                      var formData = {'page':page};
                      await requset('homePageBelowContent',formData: formData).then((val){
                          var data = json.decode(val.toString());
                          List<Map> newGoodsList = (data['data'] as List).cast();
                          setState(() {
                            hotGoodsList.addAll(newGoodsList);
                            page++;
                          });
                      });
                    },
                    onRefresh: () async {
                      print('开始加载更多');
                      page = 1;
                      var formData = {'page':page};
                      await requset('homePageBelowContent',formData: formData).then((val){
                          var data = json.decode(val.toString());
                          List<Map> newGoodsList = (data['data'] as List).cast();
                          setState(() {
                            hotGoodsList.clear();
                            hotGoodsList.addAll(newGoodsList);
                            page++;
                          });
                      });
                    },
                 );
               }else{
                 return Center(
                   child: CircularProgressIndicator(),
                 );
               }
             },
           ),
       )
    );
  }
  void _getHotlist() async {
      var formData = {'page':page};
      await requset('homePageBelowContent',formData: formData).then((val){
          var data = json.decode(val.toString());
          List<Map> newGoodsList = (data['data'] as List).cast();
          setState(() {
            hotGoodsList.addAll(newGoodsList);
            page++;
      });
    });
  }
  //火爆专区标题
  Widget hotTitle = Container(
    margin: EdgeInsets.all(10.0),
    height: ScreenUtil().setHeight(40.0),
    alignment: Alignment.center,
    color:Colors.transparent,
    child: Text('火爆专区'),
  );

  //流式布局（火爆专区）
  Widget _wrapList(){
    if(hotGoodsList.isNotEmpty){
      List<Widget> listWidget = hotGoodsList.map((val){
        return InkWell(
          onTap:(){
            Application.router.navigateTo(context,"/detail?id=${val['goodsId']}",transition:TransitionType.inFromRight,transitionDuration:const Duration(milliseconds: 150));
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(5.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                FadeInImage.memoryNetwork(
                   placeholder: kTransparentImage,
                   image:val['image'],
                   width:ScreenUtil().setWidth(370),
                ),
                Text(val['name'],maxLines: 1,overflow: TextOverflow.ellipsis,style: TextStyle(color:Colors.pink,fontSize: ScreenUtil().setSp(26)),),
                Row(
                  children: <Widget>[
                    Text('￥${val['mallPrice']}',style: TextStyle(color: Colors.redAccent),),
                    Text('￥${val['price']}',style: TextStyle(color: Colors.black26,decoration: TextDecoration.lineThrough),)
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();

      return Wrap(
        spacing: 2,
        children: listWidget,
      );
    } else {
      return Text('');
    }
  }
  //火爆专区组合
  Widget _hotGoods(){
    return Container(
      child: Column(
        children: <Widget>[
          hotTitle,
          _wrapList()
        ],
      ),
    );
  }
}
//轮播
class SwiperDiy extends StatelessWidget {
  final List swiperDateList;
  const SwiperDiy({Key key,this.swiperDateList}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    //ScreenUtil.instance = ScreenUtil(width: 750.0,height:1335.0)..init(context);
    print('设备像素密度:${ScreenUtil.pixelRatio}');
    print('设备的高:${ScreenUtil.screenHeight}');
    print('设备的宽:${ScreenUtil.screenWidth}');
    return Container(
      height: ScreenUtil().setHeight(333.0),
      width: ScreenUtil().setWidth(750.0),
      child: Swiper(
        itemCount: swiperDateList.length,
        itemBuilder: (BuildContext context,int index){
          return InkWell(
            child: Image.network("${swiperDateList[index]['image']}",fit: BoxFit.fill),
            onTap:(){
              Application.router.navigateTo(
                context,
                "/detail?id=${swiperDateList[index]['goodsId']}",
                transition:TransitionType.inFromRight,
                transitionDuration:const Duration(milliseconds: 120)
              );
            } ,
          );
        },
        pagination: SwiperPagination(),
        autoplay: true,
      ),
    );
  }
}
//导航
class TopNavgator extends StatelessWidget {
  final List navigatorList;
  const TopNavgator({Key key,this.navigatorList}) : super(key: key);
  Widget _gridViewItemUI(BuildContext context,item){
    return InkWell(
      onTap: null,
      child: Column(
        children: <Widget>[
          Image.network(item['image'],width: ScreenUtil().setWidth(95)),
          Text(item['mallCategoryName'])
        ],
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    if(this.navigatorList.length > 10){
      this.navigatorList.removeRange(10, navigatorList.length);
    }
    return Container(
      height: ScreenUtil().setHeight(280),
      padding: EdgeInsets.all(3.0),
      color: Colors.white,
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),//禁止滚动
        crossAxisCount: 5,
        padding: EdgeInsets.all(5.0),
        children: navigatorList.map((item){
          return _gridViewItemUI(context, item);
        }).toList(),
      ),
    );
  }
}
//图片小广告
class AdBanner extends StatelessWidget {
  final String adpictute;
  const AdBanner({Key key,this.adpictute}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(top:10.0),
      padding: EdgeInsets.all(5.0),
      height:ScreenUtil().setHeight(130) ,
      child:Image.network(adpictute,fit: BoxFit.fill),
    );
  }
}
//店长电话模块
class LeaderPhone extends StatelessWidget {
  final String leaderImage;
  final String leaderPhone;
  const LeaderPhone({Key key,this.leaderImage,this.leaderPhone}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return
      Container(
          padding: EdgeInsets.all(8.0),
          margin: EdgeInsets.only(top:10.0),
          width: ScreenUtil().setWidth(750.0),
          color: Colors.white,
          height: ScreenUtil().setHeight(220.0),
          child: InkWell(
            onTap: _launchURL,
            child:Image.network(leaderImage,fit: BoxFit.cover),
          ),
      );
  }
  //打电话操作
  void _launchURL() async{
    String url = 'tel:' + leaderPhone;
    if(await canLaunch(url)){
      await launch(url);
    }else{
      throw 'url不能进行访问';
    }
  }
}
//商品推荐
class Recommend extends StatelessWidget {

  final List recmmendList;
  const Recommend({Key key,this.recmmendList}) : super(key: key);
  //标题
  Widget _titleWidget(){
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(width: 0.5,color: Colors.black12,style: BorderStyle.solid)
        )
      ),
      child: Text(
        '商品推荐',
        style: TextStyle(
          color: Colors.pink,
          fontSize: 14.0
        ),
      ),
    );
  }
  //商品单独项
  Widget  _item(int index,context) {
    return InkWell(
      onTap:(){
        //跳转详情
        Application.router.navigateTo(
          context,
          "/detail?id=${recmmendList[index]['goodsId']}",
          transition:TransitionType.inFromRight,
          transitionDuration:const Duration(milliseconds: 150)
        );
      },
      child: Container(
        height: ScreenUtil().setHeight(330.0),
        width: ScreenUtil().setWidth(250.0),
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(left: BorderSide(width: 0.5,color: Colors.black12,style: BorderStyle.solid))
        ),
        child: Column(
          children: <Widget>[
            Image.network(recmmendList[index]['image']),
            Text(
             '￥${recmmendList[index]['price']}',
              style: TextStyle(
                decoration: TextDecoration.lineThrough, //下划线
                color: Colors.grey
              ),
            ),
            Text(
             '￥${recmmendList[index]['mallPrice']}',
              style: TextStyle(
                color: Colors.redAccent
              ),
            )
          ],
        ),
      ),
    );
  }
  //横向列表
  Widget _recommendList(context){
    return Container(
      height: ScreenUtil().setHeight(330.0),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,//横向滚动
        itemCount: recmmendList.length,
        itemBuilder: (context,index){
          return _item(index,context);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top:10.0),
      child: Column(
        children: <Widget>[
          _titleWidget(),
          _recommendList(context)
        ],
      ),
    );
  }
}

//楼层标题
class FloorTitle extends StatelessWidget {
  final String pictureaddress;
  const FloorTitle({Key key,this.pictureaddress}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8.0),
      height: ScreenUtil().setHeight(220.0),
      width: ScreenUtil().setWidth(750.0),
      child: Image.network(pictureaddress,fit: BoxFit.cover),
    );
  }
}
//楼层商品
class FloorContent extends StatelessWidget {
  final List floorGoodsList;
  const FloorContent({Key key,this.floorGoodsList}) : super(key: key);
  //每一项
  Widget _goodsItems(Map goods,context){
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
        onTap:(){
          Application.router.navigateTo(
            context,
            "/detail?id=${goods['goodsId']}",
            transition:TransitionType.inFromRight,
            transitionDuration:const Duration(milliseconds: 150)
          );
        },
        child:Image.network(goods['image']),
      ),
    );
  }
  //第一行布局
  Widget _firstRow(context){
    return Row(
      children: <Widget>[
        _goodsItems(floorGoodsList[0],context),
        Column(
          children: <Widget>[
            _goodsItems(floorGoodsList[1],context),
            _goodsItems(floorGoodsList[2],context),
          ],
        )
      ],
    );
  }
  //第二行布局
  Widget _otherGoods(context){
    return Row(
      children: <Widget>[
         _goodsItems(floorGoodsList[3],context),
         _goodsItems(floorGoodsList[4],context),
      ],
    );
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
       children: <Widget>[
         _firstRow(context),
         _otherGoods(context)
       ],
      ),
    );
  }
}

